package com.ruoyi.api.daoru;


import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.util.HashMap;
import java.util.Map;

/**
 * 通用状态转换器，支持多种枚举类型
 */
public class StatusConverter implements Converter<Integer> {
    // 注册枚举类型映射
    private static final Map<Class<?>, Class<? extends Enum<?>>> ENUM_MAPPING = new HashMap<>();

    static {
        // 注册User类的状态枚举
        ENUM_MAPPING.put(User.class, User.Status.class);
        // 注册ImportAddress类的状态枚举
        ENUM_MAPPING.put(ImportAddress.class, ImportAddress.StatusAddress.class);
    }

    @Override
    public Class<?> supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                     GlobalConfiguration globalConfiguration) {
        String text = cellData.getStringValue();
        if (text == null) return null;

        // 获取当前处理的类
        Class<?> targetClass = contentProperty.getField().getDeclaringClass();
        // 获取对应的枚举类型
        Class<? extends Enum<?>> enumClass = ENUM_MAPPING.get(targetClass);

        if (enumClass == null) {
            throw new IllegalArgumentException("未注册的枚举类型: " + targetClass.getName());
        }

        // 使用反射调用枚举的getCodeByText方法
        try {
            java.lang.reflect.Method method = enumClass.getMethod("getCodeByText", String.class);
            return (Integer) method.invoke(null, text);
        } catch (Exception e) {
            throw new RuntimeException("枚举转换失败", e);
        }
    }
}
